<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        placeholder="角色名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      <el-button v-waves class="filter-item" type="primary" icon="Search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="Plus" @click="handleCreate">
        添加角色
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80">
        <template #default="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色名称" width="150px" align="center">
        <template #default="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色描述" min-width="200px" align="center">
        <template #default="{row}">
          <span>{{ row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100px" align="center">
        <template #default="{row}">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="150px" align="center">
        <template #default="{row}">
          <span>{{ parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="280" class-name="small-padding fixed-width">
        <template #default="{row,$index}">
          <el-button type="primary" size="small" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="small" type="warning" @click="handlePermission(row)">
            权限配置
          </el-button>
          <el-button v-if="row.status!==0" size="small" type="success" @click="handleModifyStatus(row,'published')">
            启用
          </el-button>
          <el-button v-if="row.status!==1" size="small" @click="handleModifyStatus(row,'draft')">
            禁用
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.current" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <!-- 角色编辑对话框 -->
    <el-dialog :title="textMap[dialogStatus]" v-model="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px" style="width: 400px; margin-left:50px;">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="temp.description" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 权限配置对话框 -->
    <el-dialog title="权限配置" v-model="permissionDialogVisible" width="600px">
      <el-tree
        ref="tree"
        :data="permissionData"
        show-checkbox
        node-key="id"
        :default-expanded-keys="[1, 2, 3]"
        :default-checked-keys="checkedPermissions"
        :props="defaultProps"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="savePermissions">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination/index.vue'

const tableKey = ref(0)
const list = ref([])
const total = ref(0)
const listLoading = ref(true)
const listQuery = reactive({
  current: 1,
  pageSize: 20,
  name: undefined
})

const temp = reactive({
  id: undefined,
  name: '',
  description: ''
})

const dialogFormVisible = ref(false)
const permissionDialogVisible = ref(false)
const dialogStatus = ref('')
const currentRole = ref(null)
const tree = ref(null)

const textMap = {
  update: '编辑角色',
  create: '创建角色'
}

const rules = {
  name: [{ required: true, message: '角色名称是必填项', trigger: 'blur' }],
  description: [{ required: true, message: '角色描述是必填项', trigger: 'blur' }]
}

// 权限树数据
const permissionData = ref([
  {
    id: 1,
    label: '系统管理',
    children: [
      { id: 11, label: '用户管理' },
      { id: 12, label: '管理员管理' },
      { id: 13, label: '角色管理' }
    ]
  },
  {
    id: 2,
    label: '内容管理',
    children: [
      { id: 21, label: '文章管理' },
      { id: 22, label: '分类管理' },
      { id: 23, label: '标签管理' },
      { id: 24, label: '评论管理' }
    ]
  },
  {
    id: 3,
    label: '会员管理',
    children: [
      { id: 31, label: '会员列表' },
      { id: 32, label: '会员等级' }
    ]
  }
])

const defaultProps = {
  children: 'children',
  label: 'label'
}

const checkedPermissions = ref([])

onMounted(() => {
  getList()
})

function getList() {
  listLoading.value = true
  // 模拟数据
  setTimeout(() => {
    list.value = [
      {
        id: 1,
        name: '超级管理员',
        description: '拥有系统所有权限',
        status: 1,
        createTime: new Date()
      },
      {
        id: 2,
        name: '内容管理员',
        description: '负责内容审核和管理',
        status: 1,
        createTime: new Date()
      },
      {
        id: 3,
        name: '普通管理员',
        description: '基础管理权限',
        status: 1,
        createTime: new Date()
      }
    ]
    total.value = 3
    listLoading.value = false
  }, 1000)
}

function handleFilter() {
  listQuery.current = 1
  getList()
}

function handleModifyStatus(row, status) {
  ElMessage({
    message: '操作成功',
    type: 'success'
  })
  row.status = status === 'published' ? 1 : 0
}

function resetTemp() {
  temp.id = undefined
  temp.name = ''
  temp.description = ''
}

function handleCreate() {
  resetTemp()
  dialogStatus.value = 'create'
  dialogFormVisible.value = true
}

function handleUpdate(row) {
  temp.id = row.id
  temp.name = row.name
  temp.description = row.description
  dialogStatus.value = 'update'
  dialogFormVisible.value = true
}

function handlePermission(row) {
  currentRole.value = row
  // 模拟获取角色权限
  checkedPermissions.value = [11, 12, 21, 22]
  permissionDialogVisible.value = true
}

function createData() {
  ElMessage({
    message: '创建成功',
    type: 'success'
  })
  dialogFormVisible.value = false
  getList()
}

function updateData() {
  ElMessage({
    message: '更新成功',
    type: 'success'
  })
  dialogFormVisible.value = false
  getList()
}

function savePermissions() {
  const checkedKeys = tree.value.getCheckedKeys()
  const halfCheckedKeys = tree.value.getHalfCheckedKeys()
  const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys]
  
  ElMessage({
    message: '权限配置成功',
    type: 'success'
  })
  permissionDialogVisible.value = false
}

function handleDelete(row, index) {
  ElMessageBox.confirm('此操作将永久删除该角色, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    list.value.splice(index, 1)
    ElMessage({
      type: 'success',
      message: '删除成功!'
    })
  })
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 10px;
  
  .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 10px;
    margin-right: 10px;
  }
}
</style>